from PIL import Image
import os
import concurrent.futures


def compress_png_with_pillow(input_path, output_path, colors=256):
    """
    使用 Pillow 库压缩 PNG 图片
    :param input_path: 输入图片的路径
    :param output_path: 输出图片的路径
    :param colors: 调色板的颜色数量，默认 256
    """
    try:
        # 打开图片
        image = Image.open(input_path)
        # 转换为调色板模式
        image = image.convert('P', palette=Image.ADAPTIVE, colors=colors)
        # 保存图片
        image.save(output_path, 'PNG')
        print(f"使用 Pillow 压缩后的图片已保存到 {output_path}")
    except Exception as e:
        print(f"使用 Pillow 压缩图片时出错: {e}")


def compress_all_png_images(root_dir):
    png_files = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.lower().endswith('.png'):
                file_path = os.path.join(root, file)
                png_files.append(file_path)

    # 创建一个最大线程数为 10 的线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        # 提交任务到线程池
        futures = [executor.submit(compress_png_with_pillow, file_path, file_path) for file_path in png_files]
        # 等待所有任务完成
        concurrent.futures.wait(futures)


if __name__ == "__main__":
    root_directory = r'D:\GJ\项目\事故检测\output0311\output19\file'
    compress_all_png_images(root_directory)
